package br.com.rapidrest.util;

import java.io.File;
import java.io.FilenameFilter;
import java.net.URL;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class PackageScanner {

	private static final String DOT = ".";
	private final String CLASS_SUFFIX = ".class";
	private final FilenameFilter filter = new FilenameFilter() {
		public boolean accept(File dir, String name) {
			return name.endsWith(CLASS_SUFFIX);
			}
		};

	private String packageName;

	public PackageScanner(String packageName) {
		this.packageName = packageName;
	}

	public Set<Class<?>> scan() {
		String packagePath = packageName.replace(DOT, File.separator);
		URL dirUrl = this.getClass().getClassLoader().getResource(packagePath);
		File dir = new File(dirUrl.getFile());

		String[] classesFiles = dir.list(filter);
		HashSet<Class<?>> classes = new HashSet<Class<?>>(classesFiles.length);
		for (String name : classesFiles) {
			name = name.substring(0, name.length() - CLASS_SUFFIX.length());
			try {
				Class<?> clazz = Class.forName(packageName + DOT + name);
				classes.add(clazz);
			} catch (ClassNotFoundException e) {
				// TODO Log warn
				e.printStackTrace();
			}
		}

		return Collections.unmodifiableSet(classes);
	}

}
